package com.cy.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @Usefulness: 重写BlockExceptionHandler
 * @Author: LeiTing
 * @Date: 2021/9/22  10:22
 * @Version 1.0
 */
@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       BlockException e) throws Exception {
        //方案1.异常继续输出
        //throw e;
        //方案2.对异常内容进行处理(例如返回给客户端一个可以看得懂的信息)
        //思考：
        // 1）向客户端输出数据（写数据）用什么？输出流对象
        // 2）如何获取输出流对象？（标准的JAVAEE规范中，要借助HttpServletResp）
        // 3）当向客户端输出数据时，除了业务响应数据外，还要做什么？

        //设置响应数据编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉浏览器服务端向他响应的数据类型，以及什么编码进行显示
        //httpServletResponse.setContentType("text/html;charset=utf-8");//不能响应json
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //响应业务数据
        PrintWriter out = httpServletResponse.getWriter();
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", 429);
        if(e instanceof DegradeException){
//            out.println("<h2>服务暂时不可用</h2>");
            map.put("message","<h2>服务暂时不可用</h2>");
        }else {
//            out.println("<h2>访问太频繁，稍等片刻再访问</h2>");
            map.put("message","<h2>访问太频繁，稍等片刻再访问</h2>");
        }
        //String转json
        String jsonStr=new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();//所有字符流都要刷新

    }
}
